<template>
  <div class="self_adaption">
    <div class="g-container">
      <div class="other">
        <p class="main_text">消息模板</p>
      </div>
      <!-- 搜索 -->
      <div class="g-search">
        <div class="search_box1">
          <!-- 时间选择区域 -->
          <span class="demonstration">创建时间：</span>
          <el-date-picker
            v-model="searchValue.startAt"
            type="date"
            placeholder="开始时间"
            @change="startAt"
            :clearable="false" />
          <span class="demonstration" style="display: inline-block; font-size: 12px; color: #898989; margin: 20px"
            >至</span
          >
          <el-date-picker
            v-model="searchValue.endAt"
            type="date"
            placeholder="结束时间"
            @change="endAt"
            :clearable="false" />
          <el-radio-group v-model="radio" class="ml-4" @change="radioSelect" style="margin-left: 10px">
            <el-radio label="1" size="large">今天</el-radio>
            <el-radio label="2" size="large">近7天</el-radio>
            <el-radio label="3" size="large">近30天</el-radio>
            <el-radio label="4" size="large">近3个月</el-radio>
          </el-radio-group>

          <!-- 信息区域 -->
          <div class="all_select">
            <!-- 消息标题 -->
            <div class="input_valye">
              <span class="demonstration">模板标题：</span>
              <input
                type="text"
                class="input"
                placeholder="请输入模板标题"
                style="width: 200px; color: #606266"
                v-model="searchValue.keyword"
                @keyup.enter="search" />
            </div>
            <div class="input_valye">
              <span class="demonstration">是否启用：</span>
              <el-select v-model="searchValue.status" class="m-2" placeholder="是否启用" @change="search">
                <el-option v-for="item in status_options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="input_valye">
              <span class="demonstration">推送类型：</span>
              <el-select v-model="searchValue.type" class="m-2" placeholder="推送类型" @change="search">
                <el-option v-for="item in type_options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <!-- 底部按钮区域 -->
        <div class="bottom_btn">
          <el-button class="solid" @click="search">查询</el-button>
          <el-button class="hollow" @click="reset">重置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table">
        <!-- 表格按钮区域 -->
        <div class="table_function">
          <el-button class="solid" @click="massTexting">添加模板</el-button>
          <el-button type="danger" plain>批量删除</el-button>
        </div>
        <!-- 表格区域 -->
        <el-table
          :data="tableData"
          height="300px"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :header-cell-style="{'text-align': 'center'}"
          :show-overflow-tooltip="true"
          border>
          <el-table-column type="selection" width="40" />
          <el-table-column prop="title" label="模板标题" align="center" width="120" />
          <el-table-column prop="content" label="模板内容" align="center" />
          <el-table-column prop="status" label="是否启用" align="center">
            <template #default="item">
              <el-switch v-model="item.row.status" @change="statusChange(item.row.id)" />
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="添加时间" align="center" width="180" />
          <el-table-column prop="type" label="推送类型" align="center" width="180">
            <template #default="item">
              <el-text v-if="item.row.type == 0" class="mx-1" type="success">支付通知</el-text>
              <el-text v-if="item.row.type == 1" class="mx-1" type="info">物流通知</el-text>
              <el-text v-if="item.row.type == 2" class="mx-1" type="warning">平台公告</el-text>
              <el-text v-if="item.row.type == 3" class="mx-1" type="primary">优惠促销</el-text>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" class="operation">
            <template #default="item">
              <div class="table_btn">
                <el-button size="small" class="none" @click="lookMes(item.row)">编辑</el-button
                ><el-button size="small" class="none" @click="DelMes(item.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <smartPager
          v-model:current-page="searchValue.page"
          v-model:page-size="searchValue.rows"
          :total="Number(total)"
          @change="pageChange" />
      </div>
      <!-- 添加模板 -->
      <div class="messages" v-if="messagesShow">
        <div class="title1">
          <div class="title_mes">
            <el-icon size="20" color="#fff"><Edit /></el-icon>&nbsp;添加模板
          </div>
          <span class="close" @click="maskBtn1">✖</span>
        </div>
        <div class="content1" style="margin-top: 40px">
          <el-form ref="ruleFormRef" :model="GoodsformDate" label-width="90px" label-position="right" :rules="rules">
            <el-form-item label="标题:" prop="title">
              <el-input
                v-model="GoodsformDate.title"
                class="form_input"
                type="text"
                placeholder="请输入标题"></el-input>
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="内容:" prop="content">
              <el-input
                v-model="GoodsformDate.content"
                cols="30"
                rows="4"
                class="form_input"
                maxlength="300"
                type="textarea"
                show-word-limit
                placeholder="请输入内容"></el-input>
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="推送类型:" prop="type">
              <el-select v-model="GoodsformDate.type" class="m-2" placeholder="请选择推送类型">
                <el-option v-for="item in type_options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <span id="input_hint"></span>
            </el-form-item>
          </el-form>
          <div style="display: flex; align-items: center; font-size: 14px; color: #3d3d3d">
            <el-icon color="#116CF8" size="18"><Warning /></el-icon
            >&nbsp;发送时系统会自动在结尾追加平台名称，请勿重复添加
          </div>
          <div class="btn">
            <el-button class="hollow" @click="CancelPopUpBox">取消</el-button>
            <el-button class="solid" @click="plateformSure">确定</el-button>
          </div>
        </div>
      </div>
      <!-- 遮罩层 -->
      <div id="mask1" v-if="mask" @click="maskBtn1"></div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted, reactive} from 'vue';
import {
  RequestPlatformMessage,
  PlatformMessageAdd,
  EditTemplateStatus,
  RequestPlatformMessageEdit,
  deleteTemplate,
} from '@/api/path/index.js';
import moment from 'moment';
import {ElMessage} from 'element-plus';
import type {FormInstance} from 'element-plus';
import {Warning, Edit, User} from '@element-plus/icons-vue';
const ruleFormRef = ref<FormInstance>();

// 推送消息数据
const GoodsformDate = ref({
  title: '',
  content: '',
  type: '',
});
// 表单规则
const rules = reactive({
  type: [{required: true, message: '请选择推送类型', trigger: 'blur'}],
  // unit: [{ required: true, message: '请选择商品单位', trigger: 'change' }],
  title: [{required: true, message: '请输入推送标题', trigger: 'change'}],
  content: [{required: true, message: '请输入推送内容', trigger: 'change'}],
});
const tableData = ref<any>([]); // 表格列表
const total = ref(0); //表格总数
const mask = ref(false); //控制遮罩层显示
const messagesShow = ref(false); //控制群发显示
const order = ref<any>([]); //订单数组
const radio = ref('');
// 挂载
onMounted(() => {
  requestPlatformMessage();
});
/**
 * 获取模板列表
 */
const requestPlatformMessage = async () => {
  const a = await RequestPlatformMessage(searchValue.value);
  if (a.msg == '操作成功！') {
    total.value = a.resultObj.count;
    tableData.value = a.resultObj.list;
  }
};
/************************************  群发消息  ************************************/
const massTexting = () => {
  mask.value = true;
  messagesShow.value = true;
  type.value = 'Add';
};
/************************************  弹出框关闭  ************************************/
const CancelPopUpBox = () => {
  mask.value = false;
  messagesShow.value = false;
  GoodsformDate.value = {
    title: '',
    content: '',
    type: '',
  };
};
const type = ref('Add');
/************************************  添加模板确认  ************************************/

let timer = ref(); //设置记录时间，用于防抖
const plateformSure = async () => {
  clearTimeout(timer.value);
  timer.value = setTimeout(async () => {
    if (type.value == 'Add') {
      console.log('添加');
      const a = await new Promise((resolve, reject) => {
        PlatformMessageAdd(GoodsformDate.value)
          .then((res: any) => {
            resolve(res.resultObj);
            ElMessage.success('操作成功');
            mask.value = false;
            messagesShow.value = false;
            requestPlatformMessage();
            GoodsformDate.value = {
              title: '',
              content: '',
              type: '',
            };
          })
          .catch((err: any) => {
            reject(err);
          });
      });
    } else {
      console.log('编辑');

      const b = await new Promise((resolve, reject) => {
        RequestPlatformMessageEdit(GoodsformDate.value)
          .then((res: any) => {
            resolve(res.resultObj);
            ElMessage.success('操作成功');
            mask.value = false;
            messagesShow.value = false;
            requestPlatformMessage();
            GoodsformDate.value = {
              title: '',
              content: '',
              type: '',
            };
          })
          .catch((err: any) => {
            reject(err);
          });
      });
    }
  }, 500);
};
// 搜索参数
const searchValue = ref({
  keyword: '',
  startAt: '',
  endAt: '',
  status: '',
  type: '',
  page: 1,
  rows: 10,
});
/**
 * 时间范围单选按钮
 */
const radioSelect = () => {
  searchValue.value.startAt = '';
  searchValue.value.endAt = '';
  var now = new Date();
  now.setHours(0);
  now.setMinutes(0);
  now.setSeconds(0);
  var now1 = new Date();
  now1.setHours(23);
  now1.setMinutes(59);
  now1.setSeconds(59);
  if (radio.value === '1') {
    searchValue.value.startAt = moment(now).format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '2') {
    searchValue.value.startAt = moment(now).subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '3') {
    searchValue.value.startAt = moment(now).subtract(30, 'days').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else {
    searchValue.value.startAt = moment(now).subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  }
  search();
};
// 开始时间
const startAt = () => {
  searchValue.value.startAt.setHours(0);
  searchValue.value.startAt.setMinutes(0);
  searchValue.value.startAt.setSeconds(0);
  searchValue.value.startAt = moment(searchValue.value.startAt).format('yyyy-MM-DD HH:mm:ss');
  radio.value = '0';
  search();
};
// 结束时间
const endAt = () => {
  searchValue.value.endAt.setHours(23);
  searchValue.value.endAt.setMinutes(59);
  searchValue.value.endAt.setSeconds(59);
  searchValue.value.endAt = moment(searchValue.value.endAt).format('yyyy-MM-DD HH:mm:ss');
  radio.value = '0';
  search();
};
/**
 * 搜索
 */
const search = async () => {
  if (moment(searchValue.value.startAt).diff(moment().format('YYYY-MM-DD HH:mm:ss')) >= 0) {
    ElMessage.error('开始时间不能晚于当前日期');
    searchValue.value.startAt = '';
  } else {
    if (searchValue.value.startAt !== '' && searchValue.value.endAt !== '') {
      if (moment(searchValue.value.startAt).diff(moment(searchValue.value.endAt)) <= 0) {
        searchValue.value.page = 1;
        requestPlatformMessage();
      } else {
        ElMessage.error('结束时间不能早于开始时间');
        searchValue.value.endAt = '';
      }
    } else {
      searchValue.value.page = 1;
      requestPlatformMessage();
    }
  }
};
/**
 * 消息模板编辑
 */
const lookMes = (item: any) => {
  type.value = 'Edit';
  console.log('查看', type.value);
  messagesShow.value = true;
  mask.value = true;
  GoodsformDate.value = {
    id: item.id,
    title: item.title,
    content: item.content,
    type: item.type,
  };
};
const DelList = ref<any>([]);
/**
 * 删除消息模板
 */
const DelMes = async (item: any) => {
  DelList.value = [];
  DelList.value[0] = item.id;
  const formimgs = new FormData();
  formimgs.append('ids', DelList.value);
  const a = await deleteTemplate(formimgs);
  if (a.msg == '操作成功！') {
    ElMessage.success('删除成功');
    requestPlatformMessage();
  } else {
    ElMessage.error('删除失败');
  }
};
/**
 * 分页
 */
const pageChange = async (val: number) => {
  searchValue.value.page = val;
  requestPlatformMessage();
};
/**
 * 状态选择器
 */
const type_options = [
  {
    value: 0,
    label: '支付通知',
  },
  {
    value: 1,
    label: '物流通知',
  },
  {
    value: 2,
    label: '平台公告',
  },
  {
    value: 3,
    label: '优惠促销',
  },
];
const status_options = [
  {
    value: true,
    label: '启用',
  },
  {
    value: false,
    label: '未启用',
  },
];
/**
 * 点击重置
 */
const reset = () => {
  searchValue.value = {
    keyword: '',
    startAt: '',
    endAt: '',
    status: '',
    type: '',
    page: 1,
    rows: 10,
  };
  requestPlatformMessage();
  radio.value = '0';
};
/**
 * 表格复选框选中事件
 */
const handleSelectionChange = (selection: any) => {
  order.value = [];
  for (let x = 0; x < tableData.value.length; x++) {
    tableData.value[x].selection = false;
  }
  for (let i = 0; i < selection.length; i++) {
    selection[i].selection = true;
    order.value.push(selection[i]);
  }
};
/**
 * 修改状态
 */
const statusChange = async (id: any) => {
  const a = await EditTemplateStatus(id);
  if (a.msg != '操作成功！') {
    requestPlatformMessage();
  }
};
/**
 * 遮罩层数据
 */
const maskBtn1 = () => {
  mask.value = false;
  messagesShow.value = false;
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/plateform/Article/Content.css';
@import '@/assets/css/plateform/Shop/GoodsManage.css';
.table :deep(.el-table__cell) {
  text-align: center;
}
.nav1 {
  display: flex;
  height: 30px;
  align-items: center;
  margin-top: 20px;
  border-bottom: 0;
  .nav_li {
    width: 50%;
    height: 30px;
    line-height: 30px;
    text-align: center;
    font-size: 14px;
  }
  .current {
    border-bottom: 2px solid #5697f9;
  }
}
.table {
  overflow: hidden;
  padding: 0 10px;
  .table_function {
    margin-top: 20px;
  }
}
.el-form-item :deep(.el-input-group__prepend) {
  width: 10px;
  background-color: #116cf8;
  color: #fff;
}
.el-form-item :deep(.el-upload--picture-card) {
  height: 100px;
  width: 100px;
  opacity: 0;
}

.btn {
  width: 150px;
  position: absolute;
  right: 20px;
  bottom: 40px;
}
// 推送消息
.plateform,
.messages {
  width: 600px;
  height: 500px;
  position: absolute;
  position: fixed;
  top: 50%;
  left: 50%;
  margin-left: -300px;
  margin-top: -250px;
  z-index: 99;
  background: #fff;
}
.messages {
  height: 400px;
  margin-top: -200px;
}
:deep(.el-input__wrapper) {
  width: 200px;
}
:deep(.el-drawer.rtl) {
  background: #fff;
  width: 750px !important;
}
:deep(.el-overlay) {
  z-index: 40 !important;
  padding: static;
}

:deep(.is-process) {
  color: #409eff;
}
:deep(.is-process .el-step__icon.is-text) {
  border: 2px solid #409eff;
  background: #409eff;
  color: #fff;
}
:deep(.is-finish .el-step__line) {
  background: #409eff;
}
.el-table .warning-row {
  background: #44a2ff !important;
}
:deep(.el-select) {
  width: 100%;
}
</style>
